package com.cloudxingkong.dianyinke.NewTeacher.Ui;


import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.cloudxingkong.dianyinke.NewTeacher.Adapter.HomeLoopAdapter;
import com.cloudxingkong.dianyinke.NewTeacher.Utils.CookieHelper;
import com.cloudxingkong.dianyinke.NewTeacher.Utils.HttpUtils;
import com.cloudxingkong.dianyinke.NewTeacher.Utils.SysExitUtil;
import com.cloudxingkong.dianyinke.NewTeacher.Utils.THomePicJsonUtils;
import com.cloudxingkong.dianyinke.NewTeacher.bean.QryTeacher;
import com.cloudxingkong.dianyinke.NewTeacher.config.Constans;
import com.cloudxingkong.dianyinke.R;
import com.cloudxingkong.dianyinke.Uri.teacherUri.ThisUri;
import com.cloudxingkong.dianyinke.Widgets.MyGridLayout;
import com.google.gson.Gson;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;


public class TeacherMainActivity extends AppCompatActivity implements AMapLocationListener {

    private long exitTime = 0;
    private int mDemoPosition = 0;
    private final int FAKE_DEMO_SIZE = 100;
    private final int DEFAULT_DOT_SIZE = 4;

    private ViewPager viewPager;
    private MyGridLayout grid;
    private List<HashMap<String, String>> data;
    private ImageView[] ivDots;
    private Timer timer = new Timer();
    private HomeLoopAdapter adapter;
    private SharedPreferences sharedPreferences;
    private String sessionID;
    private boolean isUserTouched = false;
    public boolean isGPS = false;

    //定位
    private AMapLocationClientOption locationOption = null;
    private AMapLocationClient mlocationClient = null;


    private int[] srcs = {R.mipmap.iconfont_kecheng_2x, R.mipmap.iconfont_xuesheng_2x,
            R.mipmap.iconfont_bofang_2x, R.mipmap.iconfont_quanzi_2x,
            R.mipmap.iconfont_wode_2x, R.mipmap.iconfont_jianli_2x};
    private String titles[] = {"上传课程", "预约管理", "上传视频", "学生圈", "个人中心", "履历管理"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.teacher_activity_main_backup);


        grid = (MyGridLayout) findViewById(R.id.list);
        grid.setGridAdapter(new MyGridLayout.GridAdatper() {

            @Override
            public View getView(int index) {
                View view = getLayoutInflater().inflate(R.layout.actions_item,
                        null);
                ImageView iv = (ImageView) view.findViewById(R.id.iv);
                TextView tv = (TextView) view.findViewById(R.id.tv);
                iv.setImageResource(srcs[index]);
                tv.setText(titles[index]);
                return view;
            }

            @Override
            public int getCount() {
                // TODO Auto-generated method stub
                return titles.length;
            }
        });
        grid.setOnItemClickListener(new MyGridLayout.OnItemClickListener() {

            @Override
            public void onItemClick(View v, int index) {
                switch (index) {
                    case 0:
                        startActivity(new Intent(TeacherMainActivity.this, UploadWork.class));
                        break;
                    case 1:
                        startActivity(new Intent(TeacherMainActivity.this, MyStudent.class));
                        break;
                    case 2:
                        startActivity(new Intent(TeacherMainActivity.this, UploadVideo.class));
                        break;
                    case 3:
                        startActivity(new Intent(TeacherMainActivity.this, MineCircleActivity.class));
                        break;
                    case 4:
                        startActivity(new Intent(TeacherMainActivity.this, MineCenterActivity.class));
                        break;
                    case 5:
                        Intent intent = new Intent(TeacherMainActivity.this, UploadResume.class);
                        startActivityForResult(intent, 151);
                        break;
                    default:
                        break;

                }
            }
        });


        SysExitUtil.activityList.add(this);
        mlocationClient = new AMapLocationClient(getApplicationContext());
        mlocationClient.setLocationListener(this);
        init();
        //读取老师资料
        qryTeacher();
        loadLocation();
        isGPSEnabled();
    }

    private void loadLocation() {
        locationOption = new AMapLocationClientOption();
        locationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        locationOption.setNeedAddress(true);
        locationOption.setMockEnable(false);
        locationOption.setLocationCacheEnable(true);
        locationOption.setInterval(Constans.SPLASH_DISPLAY_LENGHT);
        mlocationClient.setLocationOption(locationOption);
        mlocationClient.startLocation();
    }


    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (aMapLocation != null) {
            if (aMapLocation.getErrorCode() == 0) {
                aMapLocation.getLocationType();
                aMapLocation.getLatitude(); //纬度
                aMapLocation.getLongitude(); //经度
                String address = aMapLocation.getAddress();//地址
                SharedPreferences.Editor edit = sharedPreferences.edit();
                edit.putString("Laddress", address);
                edit.commit();

                Log.e("test", "高德定位地址 " + address + "\naddress inside sp : " + sharedPreferences.getString("Laddress", ""));
            }
        } else {
            Log.e("test", "locationError , code = " + aMapLocation.getErrorCode() + "\ninfo " + aMapLocation.getErrorInfo());
        }
    }

    private void isGPSEnabled() {
        isGPS = HttpUtils.isGPSEnabled(this);
        if (!isGPS) {
            new AlertDialog.Builder(this)
                    .setTitle("提示")
                    .setMessage("检测到您未开启GPS。打开GPS将更方便于您的定位，是否前去设置打开？")
                    .setNegativeButton("取消", null)
                    .setPositiveButton("好的", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                            startActivity(intent);
                        }
                    }).create().show();
        }
    }


    private void qryTeacher() {
        sessionID = CookieHelper.getSessionID(sharedPreferences);

        RequestParams params = new RequestParams(ThisUri.SERVER_YUMING + ThisUri.THIS_RESUME);
        params.addHeader("cookie", sessionID);

        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Message msg = handler.obtainMessage();
                msg.what = 1;
                msg.obj = result;
                handler.sendMessage(msg);
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.e("test", "获取老师资料失败");
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }


    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {
                String result = (String) msg.obj;
                Log.e("test", "老师资料 " + result);
                Gson gson = new Gson();
                QryTeacher objBean = gson.fromJson(result, QryTeacher.class);
                if (objBean.isSuccess() == true) {
                    QryTeacher.ObjBean obj = objBean.getObj();
                    String name = obj.getMemname();
                    String workEpc = obj.getWorkepc();
                    String qianMing = obj.getSignature();
                    String aliasname = obj.getAliasname();
                    String glory = obj.getGlory();
                    String presentjob = obj.getPresentjob();
                    String inst = obj.getInst();
                    String phone = obj.getPhone();
                    String noPay = obj.getNopay() + "";
                    String payed = obj.getPayed() + "";
                    int seniority = obj.getSeniority();
                    int gender = obj.getGender();
                    String avatar = obj.getAvatar();
                    SharedPreferences.Editor edit = sharedPreferences.edit();
                    edit.putString("qryTid", obj.getId() + "");
                    edit.putString("qryTname", name);
                    edit.putString("qryTepc", workEpc);
                    edit.putString("qryTsignature", qianMing);
                    edit.putString("qryTAliasname", aliasname);
                    edit.putString("qryTgender", gender + "");
                    if (avatar != null) {
                        edit.putString("qryTavatar", avatar + "");
                    }
                    edit.putString("qryTseniorty", seniority + "");
                    edit.putString("qryTphone", phone);
                    edit.putString("qryTnopay", noPay);
                    edit.putString("qryTpayed", payed);
                    edit.putString("qryTglory", glory);
                    edit.putString("qryTpresentjob", presentjob);
                    edit.putString("qryTinst", inst);

                    edit.commit();
                }

            }
        }
    };

    private void loadPic() {
        x.http().get(new RequestParams(ThisUri.SERVER_YUMING + ThisUri.HOME_PIC_LIST),
                new Callback.CommonCallback<String>() {
                    @Override
                    public void onSuccess(String result) {
                        dealWithResponse(result);
                    }

                    @Override
                    public void onError(Throwable ex, boolean isOnCallback) {

                    }

                    @Override
                    public void onCancelled(CancelledException cex) {

                    }

                    @Override
                    public void onFinished() {

                    }
                });
    }

    private void dealWithResponse(String result) {
        data = THomePicJsonUtils.getPathFormJson(result);
        adapter = new HomeLoopAdapter(viewPager, data, this);
        viewPager.setAdapter(adapter);
    }


    /**
     * 监听返回按钮
     *
     * @param keyCode
     * @param event
     * @return
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                Toast.makeText(TeacherMainActivity.this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
                System.exit(0);
            }
            return true;
        }
        return false;
    }

    private TimerTask timerTask = new TimerTask() {
        @Override
        public void run() {
            if (!isUserTouched) {
                mDemoPosition = (mDemoPosition + 1) % FAKE_DEMO_SIZE;
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (mDemoPosition == FAKE_DEMO_SIZE - 1) {
                            viewPager.setCurrentItem(DEFAULT_DOT_SIZE - 1, false);
                        } else {
                            viewPager.setCurrentItem(mDemoPosition);
                        }
                    }
                });
            }
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 151) {
            if (resultCode == 152) {
                qryTeacher();
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    //初始化
    private void init() {
        sharedPreferences = getSharedPreferences("data_dyk", 0);
        viewPager = (ViewPager) findViewById(R.id.teach_home_viewpager);
        data = new ArrayList<>();
        ivDots = new ImageView[]{
                (ImageView) findViewById(R.id.iv_dot1),
                (ImageView) findViewById(R.id.iv_dot2),
                (ImageView) findViewById(R.id.iv_dot3),
                (ImageView) findViewById(R.id.iv_dot4)};

        loadPic();

        viewPager.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                int action = event.getAction();
                if (action == MotionEvent.ACTION_DOWN || action == MotionEvent.ACTION_HOVER_MOVE) {
                    isUserTouched = true;
                } else if (action == MotionEvent.ACTION_UP) {
                    isUserTouched = false;
                }
                return false;
            }
        });

        timer.schedule(timerTask, 3000, 3000);
        initEvent();

    }

    private void initEvent() {
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                mDemoPosition = position;
                setDot(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    private void setDot(int position) {
        position %= DEFAULT_DOT_SIZE;
        for (ImageView dot : ivDots) {
            dot.setImageResource(R.drawable.dot_normal);
        }
        ivDots[position].setImageResource(R.drawable.dot_focused);
    }


}
